package com.huawei.esdk.uc.sametime.popup.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.ibm.collaboration.realtime.livenames.GroupSelection;
import com.ibm.collaboration.realtime.livenames.PersonSelection;
import com.ibm.collaboration.realtime.people.Group;
import com.ibm.collaboration.realtime.people.Person;
import com.ibm.rcp.realtime.livenames.LiveName;
import com.ibm.rcp.realtime.livenames.LiveNameSelection;

/**
 * Handles common functions like mapping
 * the selection to <code>LiveName</code> or
 * <code>Group</code> instances.
 */

public class AbstractObjectActionDelegate implements
		IObjectActionDelegate {
	IStructuredSelection ss;

	public void setActivePart(IAction action, IWorkbenchPart part) {
	}

	public void run(IAction action) {
	}

	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection)
			ss = (IStructuredSelection) selection;
		else
			ss = null;
	}

	@SuppressWarnings("unchecked")
    protected LiveName[] getSelectedLivenames() {
		if (ss == null)
			return new LiveName[0];

		List items = ss.toList();
		List livenames = new ArrayList();
		for (Iterator it = items.iterator(); it.hasNext();) {
			Object item = it.next();
			if (item instanceof LiveNameSelection) {
				LiveNameSelection livenameSelection = (LiveNameSelection) item;
				LiveName livename = livenameSelection.getLiveName();
				livenames.add(livename);
			}
		}
		return (LiveName[]) livenames.toArray(new LiveName[livenames.size()]);
	}

	@SuppressWarnings("unchecked")
    protected Group[] getSelectedGroups() {
		if (ss == null)
			return new Group[0];

		List items = ss.toList();
		List groups = new ArrayList();
		for (Iterator it = items.iterator(); it.hasNext();) {
			Object item = it.next();
			if (item instanceof GroupSelection) {
				GroupSelection groupSelection = (GroupSelection) item;
				Group group = groupSelection.getGroup();
				groups.add(group);
			}
		}
		return (Group[]) groups.toArray(new Group[groups.size()]);
	}
	
	@SuppressWarnings("unchecked")
    protected Person[] getSelectedPersons() {
		if (ss == null)
			return new Person[0];

		List items = ss.toList();
		List persons = new ArrayList();
		for (Iterator it = items.iterator(); it.hasNext();) {
			Object item = it.next();
			if (item instanceof PersonSelection) {
				PersonSelection personSelection = (PersonSelection) item;
				Person person = personSelection.getPerson();
				persons.add(person);
			}
		}
		return (Person[]) persons.toArray(new Person[persons.size()]);
	}

}
